<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Product;
use app\common\model\ProductService;
use app\common\model\ProductSpecValue;
use app\common\model\Spec;
use app\common\tool\Result;
use think\Response;

class BusinessProduct extends Base
{

    /**
     * @return Response
     * 原点 2022年12月27日15:32:33 商家的商品列表
     */
    public function index()
    {
        $map = ['business_id' => $this->business->id, 'examine_status' => 2];
        $param = $this->request->get();
        switch ($param['type']) {
            case 1:
                $map['is_del'] = 0;
                $map['status'] = 1;
                break;
            case 2:
                $map['examine_status'] = 1;
                $map['examine_del'] = 0;
                break;
            case 3:
                $map['is_del'] = 0;
                $map['status'] = 0;
                break;
            case 4:
                $map['examine_status'] = 3;
                $map['examine_del'] = 0;
                break;
            default:
                return Result::fail('type值错误');
        }
        $like = [];
        if (isset($param['keyword']) && $param['keyword']) {
            $like = ['field' => 'title', 'keyword' => $param['keyword']];
        }
        $list = Product::getPageList($map, 'id,title,price,vip_price,icon,status,examine_status,examine_msg', $this->getPage(),
            $this->getLimit(), false, '', '', '', $like);
        return Result::fastReturn($list);
    }

    /**
     * @param $id - 商品ID
     * @return Response
     * 原点 2022年12月27日16:07:29 商品详情
     */
    public function read($id): Response
    {
        try {
            $map = ['business_id' => $this->business->id, 'id' => $id];
            $info = Product::where($map)->with(['cate1', 'cate2', 'cate3'])
                ->field('id,title,cate_1,cate_2,cate_3,images,price,vip_price,stock,
                freight,content_text,content_images,business_pick,service,status,examine_status,examine_msg')
                ->find();
            if (empty($info)) {
                return Result::fail('商品不存在');
            }
            $info->content_text = $info->content_text ?: '';
            $service = ProductService::where(['is_del' => 0, 'status' => 1])->field('id,title,explain')->select();
            $productService = $info->service ? explode(',', $info->service) : [];
            foreach ($service as &$item) {
                if ($productService && in_array($item->id, $productService)) {
                    $item->checked = 1;
                } else {
                    $item->checked = 0;
                }
            }
            $info->serviceText = $service;
            return Result::success('success', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @param $id
     * @return Response
     * 原点 2022年12月27日16:45:39 获取商品规格 - 编辑商品时
     */
    public function getSpec($id): Response
    {
        try {
            $map = ['business_id' => $this->business->id, 'id' => $id];
            $info = Product::where($map)->field('id,cate_3')->find();
            if (empty($info)) {
                return Result::fail('商品不存在');
            }
            $result = Spec::getSpec($info->cate_3, 'cate_3', $info->id, $this->business->id, $api=true);
            if ($result['code'] != 1) {
                return Result::fail('获取失败');
            }
            return Result::success('success', ['spec' => $result['result']['specData'], 'sku' => $result['result']['skuData']]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @param $id
     * @return Response
     * 原点 2022年12月27日16:45:39 获取商品规格 - 添加商品
     */
    public function getCateSpec($cate_3): Response
    {
        try {
            $result = Spec::getSpec($cate_3, 'cate_3', '', $this->business->id);
            if ($result['code'] != 1) {
                return Result::fail('获取失败');
            }
            return Result::success('success', ['spec' => $result['result']['specData'], 'sku' => $result['result']['skuData']]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2022年12月29日11:12:00 获取商品服务
     */
    public function getService(): Response
    {
        try {
            $map = ['is_del' => 0, 'status' => 1];
            $data = ProductService::where($map)->field('id,title,explain')->select();
            return Result::success('success', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2022年12月26日14:48:24 商家添加修改商品
     */
    public function save(): Response
    {
        try {
            $param = $this->request->post();
            $this->validate($param, 'Product');
            //处理数据
            $skus = [];
            foreach ($param['skus'] as $k => $item) {
                $skus[$item['sku_id']] = $item;
                unset($skus[$item['sku_id']]['sku_id']);
                unset($skus[$item['sku_id']]['sku_item']);
            }
            $param['skus'] = $skus;
            $param['business_id'] = $this->business->id;
            $msg = '已添加，请耐心等待审核！';
            if (isset($param['id']) && $param['id']) {
                $info = Product::where('id', $param['id'])->field('id,examine_status')->find();
                if ($info->examine_status == 3) {
                    $param['create_time'] = time();
                    $param['examine_status'] = 1;
                    $param['examine_time'] = 0;
                    $param['examine_admin_id'] = 0;
                    $param['examine_admin_name'] = '';
                    $param['examine_msg'] = '';
                    $msg = '已重新提交申请，请耐心等待审核！';
                }
            }
            return Result::fastReturn(Product::_saveSpec($param, $this->business, $msg));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2022年12月27日15:39:14 删除商品
     */
    public function update(): Response
    {
        try {
            $param = $this->request->post();
            $key = $param['key'];
            if (!in_array($key, ['examine_del', 'is_del', 'status'])) {
                return Result::fail('key错误');
            }
            $map = ['business_id' => $this->business->id, 'id' => $param['id']];
            $info = Product::where($map)->find();
            if (empty($info)) {
                return Result::fail('商品不存在');
            }
            if ($key != 'status') {
                $msg = '已删除';
            } else {
                $msg = $param['value'] == 1 ? '已上架' : '已下架';
            }
            $info->$key = $param['value'];
            $info->save();
            return Result::success($msg);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2022年12月28日09:02:03 修改库存
     */
    public function updateStock(): Response
    {
        try {
            $param = $this->request->post('stock');
            foreach ($param as $k => $v) {
                ProductSpecValue::update(['stock' => $v['stock'], 'id' => $v['id']]);
            }
            return Result::success('已保存');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}

